#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <cerrno>
#include "Comm.hpp"
#include "Log.hpp"
using namespace LogModule;
int main(int argc, char *argv[])
{

    if (argc != 3)
    {
        std::cout << "Usage Error:" << "id port" << std::endl;
        Die(USAGEERR);
    }
    std::string ip = argv[1];
    uint16_t port = std::atoi(argv[2]);
    // 1.创建socket套接字
    int sockfd;
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "socket error";
        std::cerr << strerror(errno);
        Die(SOCKETERR);
    }
    LOG(LogLevel::INFO) << "socket success sockfd:" << sockfd;
    // 客户端不需要绑定？
    // 必须要有自己的ip和port
    //不需要显示调用bind，而是客户端首次sendto，由os自动调用bind
    //
    struct sockaddr_in local;
    socklen_t len = sizeof(struct sockaddr_in);
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    local.sin_addr.s_addr = inet_addr(ip.c_str());
    while(true)
    {
        std::cout<<"Please Enter# ";
        struct sockaddr_in peer;
        socklen_t peer_len;
        std::string s;
        std::cin>>s;
        sendto(sockfd,s.c_str(),s.size(),0,CONV(&local),len);
        //std::cout<<"sento success"<<std::endl;
        char buffer[1024];
        int n = recvfrom(sockfd,buffer,sizeof(buffer),0,CONV(&peer),&peer_len);
        if(n>0)
        {
            buffer[n] = 0;
            std::cout<<buffer<<std::endl;
        }
    }


    return 0;
}